﻿using DailyPoetryM.Models;
using System.Data;
using System.Data.Common;
using System.Linq.Expressions;

using System.Data.SqlClient;
using SQLite;

namespace DailyPoetryM.Services;

public class PoetryStorage: IPoetryStorage
{
    // 资源路径
    public const string DbName = "poetrydb.sqlite3";
    public static readonly string PoetryDbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), DbName);

    // 新增数据库连接（嵌入式资源的单元测试，第二部门；创建GIT仓库）
    private SQLiteAsyncConnection? _connection;
    private SQLiteAsyncConnection Connection => _connection ??= new SQLiteAsyncConnection(PoetryDbPath);


    //新增修改
    private readonly IPreferenceStorage _preferenceStorage;
    public PoetryStorage(IPreferenceStorage preferenceStorage)
    {
        _preferenceStorage = preferenceStorage;
    }


    //初始化，修改

    public bool IsInitialized =>
        _preferenceStorage.Get(PoetryStorageConstant.VersionKey, 0) == PoetryStorageConstant.Version;//TRUE or FALSE
    // public bool IsInitialized => Preferences.Get(PoetryStorageConstant.VersionKey, 0) == PoetryStorageConstant.Version;//TRUE or FALSE

    //数据库初始化
    public async Task InitializeAsync()
    {
        //打开文件
        await using var dbFileStream = 
            new FileStream(PoetryDbPath, FileMode.OpenOrCreate);
        //打开资源
        await using var dbAssetStream =
            typeof(PoetryStorage)//Type
            .Assembly             //Assembly
            .GetManifestResourceStream(DbName);
        if(dbAssetStream is null)
        {
            throw new Exception($"地址为{PoetryDbPath}，找不到名为{DbName}的资源");
        }
        //文件拷贝到资源
        await dbAssetStream.CopyToAsync(dbFileStream);
        //保存版本号
        _preferenceStorage.Set(PoetryStorageConstant.VersionKey,PoetryStorageConstant.Version);//保存版本号
    }

    public async Task<Poetry> GetPoetryAsync(int id) =>
        await Connection.Table<Poetry>().FirstOrDefaultAsync(p => p.Id == id);
    //select * from Poetry where "Id" = @id



    public async Task<IEnumerable<Poetry>> GetPoetriesAsync(
        Expression<Func<Poetry, bool>> where, int skip, int take) =>
        await Connection.Table<Poetry>().Where(where).Skip(skip).Take(take)
        .ToListAsync();
    //select * from Poetry where title ="" and title="" and author =""
    // skip是跳过多少条结果，take是返回多少条结果


    //关闭数据库,接口没写
    public async Task CloseAsync()=>await Connection.CloseAsync();


}
//诗词存储常量，存储和比较版本号
public static class PoetryStorageConstant
{
    //正确的版本号
    public const int Version = 1;

    //偏好存储存着的版本
    public const string VersionKey = nameof(PoetryStorageConstant) + "." + nameof(Version);

    // nameof(PoetryStorageConstant)                         ->     "PoetryStorageConstant"  类名变成支付查查
    // nameof(Version)                                       ->     "Version"
    // nameof(PoetryStorageConstant) + "."+nameof(Version);  ->     "PoetryStorageConstant.Version"

}
